# event
from Shell.fsm.EventDefine import event_NETWORKGAME_BACKTOMAINMENU,event_NETWORKGAME_GAMELOBBY
# uiString
from Shell.data.UIString import uiString
from Cube.map import QMemberType

class LoginController:
    def __init__(self,
                 model,
                 view):

        self.model = model
        self.view = view
        self.ButtonOn = False
        self.ReserveWordList = [uiString[QMemberType.COMPUTER],
                                uiString[QMemberType.OPEN],
                                uiString[QMemberType.CLOSE]
                                ]

        self.view.ControllerSet(self)

    def NickNameSetHandle(self, text):
        self.view.entry_Nickname.setFocus()

    def IPAddressSetHandle(self, text):
        self.view.entry_IP.setFocus()

    def LoginHandle(self):
        if self.ButtonOn:
            return # to avoid re-enter LoginHandle
        else:
            self.ButtonOn = True

        # check data
        nickname = self.view.entry_Nickname.get(plain = True)
        if not nickname:
            self.view.LoginFailDisplay(uiString["Please enter your nickname"])
            return
        elif nickname in self.ReserveWordList:
            self.view.LoginFailDisplay("'%s'%s"%(nickname,uiString["is a reserve word"]))
            return
        else:
            self.model.Nickname = nickname

        bSuccess = self.model.IPSet(self.view.entry_IP.get(plain = True))
        if not bSuccess:
            self.view.LoginFailDisplay(uiString["Please enter host's ip address"],
                                       self.ErrorDisplayDialogDestroy)
            return
        # now all data is valid

        bSuccess = self.model.GameLobbyCreateHandle()
        # push GameLobbyFSM state change if connect success
        if bSuccess:
            messenger.send(event_NETWORKGAME_GAMELOBBY)
        else:
            self.view.LoginFailDisplay(uiString["Can not establish link"],
                                       self.ErrorDisplayDialogDestroy)

    def BackToMainMenuHandle(self):
        messenger.send(event_NETWORKGAME_BACKTOMAINMENU)

    def ErrorDisplayDialogDestroy(self, value):
        self.view.ErrorDisplayDialogDestroy()
        self.ButtonOn = False
